<template>
	<view>
		<!-- <u-navbar title="发布" :bgColor="bgColor" leftIconColor="#fff" :titleStyle="titleStyle" :placeholder="true"
			:autoBack="true"></u-navbar> -->
		<headerinfo></headerinfo>
		<!-- <headertop></headertop> -->
		<backos title="上一步"></backos>
		<view class="page">
			<view class="yulan">
				<view class="title">{{form.title}}</view>
				<!-- <view class="fengmian" @click="chooseImage" v-if="!form.posterUrl">
					<i class="iconfont">&#xe68e;</i>
					<view class="">添加封面图</view>
				</view> -->
				<view class="fengmian" @click="chooseImage" v-if="form.posterUrl">
					<image class="fengmianImg" :src="form.posterUrl" mode="aspectFill"></image>
				</view>
			</view>
			<view class="lineBox"></view>
			<u-cell-group>
				<u-cell :title="form.isMylife?'生活分类':'文章分类'" @click="fenleiDia = true" :value="fenleiName?fenleiName:'请选择'"
					:isLink="true"></u-cell>
				<view class="" v-if="!familyId">
					<u-cell title="发布到哪个家庭" v-if="!form.isMylife" @click="familyDia = true"
						:value="familyName?familyName:'请选择'" :isLink="true"></u-cell>
					<u-cell title="选择参与的家庭成员" v-if="userList.length>0 && !form.isMylife" @click="userlistDia = true"
						:value="checkedUserName?checkedUserName:'请选择'" :isLink="true"></u-cell>
					<view class="kaiguanlist" v-if="!form.isMylife">
						<span>分享文章到所有人</span>
						<u-switch v-model="form.shareToAll" activeColor="#de4849"></u-switch>
					</view>
					<view class="kaiguanlist" v-if="!form.isMylife && systemUser">
						<span>分享文章到家庭美文</span>
						<u-switch v-model="form.systemArticle" activeColor="#de4849"></u-switch>
					</view>
					<view class="smalldesc" v-if="(!familyMemberId)  && (!form.isMylife)">
						共享文章，如果和自身家庭无关，可以不勾选相关家庭信息
					</view>
				</view>

			</u-cell-group>

			<view class="lastBtn">
				<span v-if="(!form.isDraftData) && (!form.isMylife)" @click.stop="submit(1)">存草稿</span>
				<span :class="(form.isDraftData) || (form.isMylife)?'isDraftDataBtn':''" class="fabu" @click.stop="submit">发布</span>
			</view>
		</view>
		<u-picker :show="fenleiDia" @cancel="fenleiDia = false" :columns="tabTitle" keyName="name"
			@confirm="fenleconfirm"></u-picker>

		<!-- 	<u-picker :show="familyDia" @cancel="familyDia = false" :columns="familylist" keyName="label"
			@confirm="familyConfim"></u-picker> -->

		<u-popup :show="familyDia">
			<selectpicker @closeDia="familyDia = false" @checkedUser="familyConfim" :list="familylist"
				@close="familyDia = false"></selectpicker>
		</u-popup>
		<u-popup :show="userlistDia">
			<selectpicker @closeDia="userlistDia = false" @checkedUser="checkedUser" :list="userList"
				@close="userlistDia = false"></selectpicker>
		</u-popup>
		<w-compress ref='wCompress' />
	</view>
</template>

<script>
	import minxins from '../../common/upload.js';
	const util = require('@/common/refresh.js');
	import WCompress from '@/components/w-compress/w-compress.vue'

	export default {
		mixins: [minxins],
		components: {
			WCompress
		},
		data() {
			return {
				bgColor: '#de4849',
				titleStyle: {
					color: '#fff'
				},
				systemUser: false, // 系统管理员
				fenleiDia: false,
				familyDia: false,
				userlistDia: false,
				tabTitle: [],
				checkedUserName: '',
				familylist: [],
				userList: [],
				familyName: '',
				fenleiName: '',
				treeData: [],
				form: {
					categoryId: '',
					content: '',
					familyAttenders: [],
					familyIds: [],
					htmlArticle: true,
					images: [],
					isDraft: false,
					shareToAll: false,
					location: '',
					systemArticle: false,
					posterUrl: '',
					title: '',
					videoCoverSeconds: '',
					videos: [],
					isMylife: '',
					privacy: 'all'
				},
				familyMemberId: '',
				familyId: ''
			};
		},

		onLoad(e) {
			this.form = JSON.parse(decodeURIComponent(e.data));

			this.form.familyIds = []

			console.log('articlenext e', e)
			if (e.familyMemberId) {
				this.familyMemberId = e.familyMemberId
			}

			if (e.familyId) {
				this.familyId = e.familyId
				this.form.familyIds = [e.familyId]
				this.checkedUserName = ''
				this.form.familyAttenders = [this.familyMemberId]
			}

			let systemUser = uni.getStorageSync('systemUser') ? uni.getStorageSync('systemUser') : false
			this.systemUser = systemUser
			console.log(this.form);
			if (this.form.images && this.form.images.length > 0) {
				this.form.posterUrl = this.form.images[0]
			}
			if (this.form.isMylife) {
				this.getAllLifeCategories();
			} else {
				this.getAllCategories();
			}
			this.getMyfamilyData()

		},
		mounted() {
			// window.removeEventListener('popstate')	
			// window.removeEventListener('popstate2')	
		},
		methods: {
			backPage() {
				uni.navigateBack()
			},
			checkedUser(e) {
				console.log(e)
				this.userlistDia = false
				if (e.length == 0) {
					return
				}
				this.form.familyAttenders = []
				this.checkedUserName = ''
				let arr = []
				e.forEach(item => {
					this.form.familyAttenders.push(item.val)
					arr.push(item.name)
				})

				this.checkedUserName = arr.toString()

			},
			submit: util.throttle(function(type) {
				console.log('submit throttle', this.form)
				if (this.form.isMylife == 1) {
					// 发生活
					if (type == 1) {
						this.form.isDraft = true
					}
					if ((!this.form.lifeCategoryId) || this.form.lifeCategoryId == '') {
						return this.$Show.show('请选择生活分类')
					}
					//草稿进来的 
					if (this.form.isDraftData) {
						this.form.isDraft = false
						this.form.lifeId = this.form.docId
					}

					if (this.familyMemberId) {
						this.form.familyMemberId = this.familyMemberId
						this.$api.upsertOtherLife(this.form).then(res => {
							if (type == 1) {
								this.$Show.show('保存成功')
							} else {
								this.$Show.show('发布成功')
							}
							if (this.form.htmlArticle) {
								uni.setStorageSync('cleararticleForm2', 1)
							} else {
								uni.setStorageSync('clearpictureForm2', 1)
							}
							uni.setStorageSync('lifeneedRefresh', 1)
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/life/index'
								})
							}, 1000)
							// setTimeout(() => {
							// 	uni.navigateBack({
							// 		delta: 3
							// 	})
							// }, 1000)
						})
					} else {
						this.$api.upsertLife(this.form).then(res => {
							if (type == 1) {
								this.$Show.show('保存成功')
							} else {
								this.$Show.show('发布成功')
							}
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/life/index'
								})
							}, 1000)
							// setTimeout(() => {
							// 	uni.navigateBack({
							// 		delta: 3
							// 	})
							// }, 1000)
						})
					}


				} else {
					// 发家庭
					if (type == 1) {
						this.form.isDraft = true
					} else {
						if (this.form.categoryId == '') {
							return this.$Show.show('请选择文章分类')
						}
						if (!this.form.shareToAll && !this.form.systemArticle) {
							if (this.form.familyIds.length == 0) {
								return this.$Show.show('请选择家庭')
							}

							if (this.form.familyIds.length == 1 && this.checkedUserName == '') {
								return this.$Show.show('请选择家庭成员')
							}
						}
					}
					//草稿进来的 
					if (this.form.isDraftData) {
						this.form.isDraft = false
						this.form.articleId = this.form.articleId ? this.form.articleId : this.form.docId
					}
					console.log('------upsertArticle----', this.form);
					this.$api.upsertArticle(this.form).then(res => {
						if (type == 1) {
							this.$Show.show('保存成功')
						} else {
							this.$Show.show('发布成功')
						}
						uni.setStorageSync('needRefresh', 1)
						if (this.form.htmlArticle) {
							uni.setStorageSync('cleararticleForm', 1)
						} else {
							uni.setStorageSync('clearpictureForm', 1)
						}

						if (type == 1) {
							setTimeout(() => {
								uni.navigateTo({
									url:"/pages/draft/index"
								})
							}, 1000)
						} else {
							console.log('reLaunch');
							// setTimeout(() => {
							// 	uni.reLaunch({
							// 		url: '/pages/tabbar/index?index=1'
							// 	})
							// }, 1000)
							setTimeout(() => {
								uni.navigateBack({
									delta: 3
								})
							}, 1000)
						}
					})
				}
			}, 1500),

			fenleconfirm(e) {
				console.log(e)
				this.fenleiName = e.value[0].name
				if (this.form.isMylife == 1) {
					this.form.lifeCategoryId = e.value[0].id
				} else {
					this.form.categoryId = e.value[0].id
				}


				this.fenleiDia = false
			},
			familyConfim(e) {
				let familyIds = []
				let familynames = []
				if (e.length > 0) {
					e.forEach(item => {
						familyIds.push(item.familyId)
						familynames.push(item.name)
					})

					this.form.familyIds = familyIds
					this.familyName = familynames.toString()
					this.familyDia = false
					if (this.form.familyIds.length == 1) {
						this.getFamUser()
					} else {
						this.userList = []
						this.checkedUserName = ''
						this.form.familyAttenders = []
					}
				}


			},
			getFamUser() {
				let data = {
					familyId: this.form.familyIds[0]
				}
				this.$api.queryFamilyMember(data).then(res => {
					console.log(res)

					let list = []

					if (res.list.length > 0) {
						res.list.forEach(item => {
							list.push({
								name: item.nickname,
								val: item.id,
								phone: item.phone,
								checked: false
							})
						})
					}


					this.userList = list
				})
			},
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: res => {
						console.log(res)
						// #ifdef MP-WEIXIN

						this.$refs.wCompress.start(res.tempFilePaths).then(res2 => {
							res2.forEach((item, index) => {
								var fileName = Date.now() + '_' + Math.round(Math.random() *
									100000000) + '.' + item.substring(item.lastIndexOf(
									'.') + 1)

								var maxImageMegBytes = uni.getStorageSync('maxImageMegBytes') ?
									uni.getStorageSync('maxImageMegBytes') : 20

								var resSize = res.tempFiles[index].size;
								if (resSize > maxImageMegBytes * 1024 * 1024) {
									uni.showToast({
										title: `大小不能超过${maxImageMegBytes}MB`,
										icon: 'none'
									});
									return
								}

								var familyId = uni.getStorageSync('familyId') ? uni
									.getStorageSync('familyId')[0] : ''


								this.uploadUserImage(item, 'image', fileName, familyId, (
									imgUrl) => {
									this.form.posterUrl = imgUrl
								})
							})
						})
						// #endif

						// #ifndef MP-WEIXIN
						// #ifdef APP-PLUS
						let houzui = res.tempFiles[0].path.substring(res.tempFiles[0].path.lastIndexOf('.') +
							1)
						// #endif

						// #ifdef H5
						let houzui = res.tempFiles[0].name.substring(res.tempFiles[0].name.lastIndexOf('.') +
							1)
						// #endif

						let name = Date.now() + '_' + Math.round(Math.random() * 100000000)
						let path = res.tempFilePaths[0]
						let fileName = name + '.' + houzui

						let maxImageMegBytes = uni.getStorageSync('maxImageMegBytes') ? uni.getStorageSync(
							'maxImageMegBytes') : 20

						let resSize = item.size;
						if (resSize > maxImageMegBytes * 1024 * 1024) {
							uni.showToast({
								title: `大小不能超过${maxImageMegBytes}MB`,
								icon: 'none'
							});
							return
						}


						let familyId = uni.getStorageSync('familyId') ? uni.getStorageSync('familyId')[0] : ''


						// #ifdef APP-PLUS
						uni.compressImage({
							src: path,
							quality: 30,
							compressedWidth: 300,
							success: res => {
								this.uploadUserImage(res.tempFilePath, 'image', fileName, familyId,
									(
										imgUrl) => {
										this.form.posterUrl = imgUrl
									})
							}
						})
						// #endif
						// #ifdef H5
						//压缩图片
						this.getImageInfo(path).then(fileUrl => {
							this.uploadUserImage(fileUrl, 'image', fileName, familyId, (
								imgUrl) => {
								this.form.posterUrl = imgUrl
							})
						})
						// #endif
						// #endif





					}
				})
			},
			getMyfamilyData() {

				this.$api.myFamily().then(res => {
					let familylist = [];
					uni.setStorageSync('myFamilyIndexs', []);
					if (res.familyInfo) {
						for (let i in res.familyInfo) {
							familylist.push({
								familyId: i,
								family: res.familyInfo[i].family
							});
						}
						if (familylist.length > 0) {
							familylist.forEach((item, index) => {
								console.log(item);
								item.name = item.label = item.family.familyName;
								item.id = item.familyId;

							});
						}

						console.log(familylist);
						this.familylist = familylist


					}
				});
			},
			getAllLifeCategories() {
				let tabBars = [];
				this.$api.getAllLifeCategories().then(res => {
					console.log(res)
					if (res) {
						for (let i in res) {
							if (this.form.lifeCategoryId) {
								if (i == this.form.lifeCategoryId) {
									this.fenleiName = res[i]
								}
							}

							tabBars.push({
								name: res[i],
								id: i,
							});

						}
						this.tabTitle.push(tabBars);


					}
				})
			},
			getAllCategories() {
				let tabBars = [];
				this.$api.getAllCategories().then(res => {
					if (res) {
						for (let i in res) {
							if (this.form.categoryId) {
								if (i == this.form.categoryId) {
									this.fenleiName = res[i]
								}
							}

							tabBars.push({
								name: res[i],
								id: i,
							});

						}
						this.tabTitle.push(tabBars);


					}
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	.smalldesc {
		padding: 20rpx;
	}

	.kaiguanlist {
		padding: 20rpx 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1px solid #e6e6e6;
	}

	.page {
		background-color: #fff;
		border-top: 1px solid #f9f9f9;
		width: 600px;
		margin: 0 auto;
		box-shadow: 0 0 3px #ccc;
		border-radius: 20rpx;

		.yulan {
			background-color: #fff;
			position: relative;
			padding-right: 250rpx;
			height: 230rpx;
			padding: 30rpx;

			.title {
				font-size: 32rpx;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 3;
				overflow: hidden;
			}

			.fengmian {
				position: absolute;
				width: 230rpx;
				height: 150rpx;
				background-color: #f8f8f8;
				right: 30rpx;
				top: 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				border-radius: 5rpx;

				.fengmianImg {
					width: 100%;
					height: 100%;
				}

				view {
					font-size: 24rpx;
					color: #b7b7b7;
					margin-top: 15rpx;
				}

				.iconfont {
					color: #b7b7b7;
					font-size: 40rpx;
				}
			}
		}

		.lineBox {
			background-color: #f2f2f2;
			height: 10rpx;
		}

		.lastBtn {
			position: fixed;
			width: 600px;
			bottom: 0;
			border-top: 1px solid #e8e8e8;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 30rpx 50rpx 30rpx;
			background-color: #fff;

			span {
				display: block;
				width: 48%;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border: 1px solid #e8e8e8;
				border-radius: 10rpx;
			}

			.fabu {
				border-color: #de4849;
				background-color: #de4849;
				color: #fff;
			}

			.isDraftDataBtn {
				width: 100% !important;
			}

		}
	}
</style>